<template>
  <div class="task-container">
    <van-nav-bar title="任务列表" fixed placeholder left-arrow @click-left="handleBack" />

    <!-- 任务列表 -->
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多任务"
      @load="loadTasks"
    >
      <van-cell
        v-for="(task, index) in taskList"
        :key="index"
        :title="task.taskName"
        :value="task.description"
      >
        <template #extra>
          <van-button
            v-if="task.status === 0"
            type="primary"
            size="small"
            @click="acceptTask(task.id)"
          >
            接受任务
          </van-button>
          <van-button
            v-if="task.status === 1"
            type="success"
            size="small"
            @click="completeTask(task.id)"
          >
            完成任务
          </van-button>
          <van-tag
            v-if="task.status === 2"
            type="success"
            size="small"
          >
            已完成
          </van-tag>
        </template>
      </van-cell>
    </van-list>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { taskListService, acceptTaskService, completeTaskService } from '@/api/task'
import { showToast } from 'vant'
import {useRouter} from 'vue-router'
const router = useRouter()
// 任务列表数据
const taskList = ref([
])
const loading = ref(false)
const finished = ref(false)
// 当前页码
const currentPage = ref(1)
// 每页显示记录数
const pageSize = ref(10)

// 加载任务列表
const loadTasks = async () => {
  if (finished.value) return
  loading.value = true
  const result = await taskListService(currentPage.value, pageSize.value)
  if (result.data.length < pageSize.value) {
    finished.value = true
  }
  taskList.value = [...taskList.value, ...result.data]
  currentPage.value++
  loading.value = false
}

// 接受任务
const acceptTask = async (taskId) => {
  const result = await acceptTaskService(taskId)
  showToast(result.description || '接受任务成功')
  // 重新加载任务列表
  taskList.value = []
  currentPage.value = 1
  finished.value = false
  loadTasks()
}

// 完成任务
const completeTask = async (taskId) => {
  const result = await completeTaskService(taskId)
  showToast(result.description || '完成任务成功')
  // 重新加载任务列表
  taskList.value = []
  currentPage.value = 1
  finished.value = false
  loadTasks()
}

onMounted(() => {
  loadTasks()
})

// 处理返回按钮点击
const handleBack = () => {
  router.push('/workbenches')
  console.log('返回上一页')
}
</script>

<style scoped>
.task-container {
  background: #f5f7fa;
  min-height: 100vh;
}
</style>